<?php
namespace app\api\controller\salesman;

use think\Controller;
use think\Request;
use think\Db;
use app\common\model\power\Rolepower;
use app\common\model\user\User as UserModel;
use app\common\model\factory\Factory as FactoryModel;
use app\api\controller\Base;
use think\facade\Env;
use app\api\controller\Pub;
use app\common\model\customer\Customer as CustomerModel;

class Customer extends Base
{
    public function initialize()
    {
        parent::initialize();
        $this->is_login();
        Rolepower::powerguard('305004'); // 销售员工管理
    }

    private function is_login()
    {
        $data =UserModel::is_sessionlogin();
        if (!$data['code']) {
            $data['options'] = 'relogin';
            json($data)->send();
            exit;
        }
    }

    // 客户列表
    public function customerList(Request $request)
    {
        $pub=new Pub();
        $user_id=$pub->userid();

        $role= Db::name('user')->where('UserId',$user_id)->value('Role');
        if ($role == 306) { // 代销售员工
            $customer_ids = Db::name('user_customer')->where('user_id', $user_id)->column('customer_id');
        } elseif ($role == 305) { // 代理商管理员
            $group_id = Db::name('user_group')->where('user_id', $user_id)->value('group_id');
            $emp_ids = Db::name('user_group')->where('group_id', $group_id)->column('user_id');
            $customer_ids = Db::name('user_customer')->whereIn('user_id', $emp_ids)->column('customer_id');
        } 

        $list = CustomerModel::whereIn('CustomerId', $customer_ids)->select();
        return json(['code'=>1, 'msg'=>'success', 'data'=>$list]);
    }

    // 添加客户
    public function customerAdd(Request $request)
    {
        $pub=new Pub();
        $user_id=$pub->userid();

        $data = $request->post();
        if (empty($data['Name']) || empty($data['Address']) || empty($data['OtherTel'])) {
            return json(['code'=>0, 'msg'=>'参数不完整']);
        }
        $customer = new CustomerModel();
        $customer->Name = $data['Name'];
        $customer->Address = $data['Address'];
        $customer->OtherTel = $data['OtherTel'];
        $customer->AddTime = date('Y-m-d H:i:s');
        $customer->save();
        // 关联到当前用户
        Db::name('user_customer')->insert([
            'user_id' => $user_id,
            'customer_id' => $customer->CustomerId,
        ]);
        return json(['code'=>1, 'msg'=>'添加成功']);
    }

    //客户删除
    public function customerDel(Request $request)
    {
        $CustomerId = $request->post('CustomerId');
        if (empty($CustomerId)) {
            return json(['code'=>0, 'msg'=>'参数不完整']);
        }
        CustomerModel::destroy($CustomerId);
        Db::name('user_customer')->where('customer_id', $CustomerId)->delete();
        return json(['code'=>1, 'msg'=>'删除成功']);
    }

}  